package com.ca.ui.core.view.bar;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearSmoothScroller;
import androidx.recyclerview.widget.RecyclerView;

import com.ca.ui.core.R;
import com.ca.ui.core.adapter.SortClubAdapter;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class SortListBar extends ConstraintLayout {

    private int currentIndex;

    private RecyclerView rv;

    public TextView currentView;
    public LinearLayout barLL;

    private final List<TextView> textViewList = new ArrayList<>();

    public SortListBar(@NonNull Context context) {
        super(context);
        initView(context);
    }

    public SortListBar(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public SortListBar(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

    private void initView(Context context) {

        View view = LayoutInflater.from(context).inflate(R.layout.sort_list_bar_layout, this);

        barLL = view.findViewById(R.id.ll_bar);

        for (int i = 0; i < 26; i++) {
            String text = String.valueOf((char) ('A' + i));
            TextView textView = new TextView(getContext());
            textView.setText(text);
            textView.setTextColor(getResources().getColor(R.color.primary_text));
            textView.setTextSize(10);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            textView.setGravity(Gravity.CENTER);
            params.weight = 1;
            textView.setLayoutParams(params);
            textViewList.add(textView);
            textView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
            barLL.addView(textView);
        }

        currentView = view.findViewById(R.id.tv_current);
        currentView.setVisibility(GONE);

        setOnClickListener(v -> {});

        //  默认选中第0项
        setCurrentIndex(0);

        //  设置侧边栏触摸事件，当点击或滑动时改变当前选中的值
        setOnTouchListener((v, event) -> {

            //  显示字符视图
            post(() -> currentView.setVisibility(VISIBLE));

            if (event.getAction() == MotionEvent.ACTION_UP) {
                //  手指抬起后，隐藏字符视图
                post(() -> currentView.setVisibility(GONE));
            }
            else {

                //  获取触摸位置
                float ey = event.getY();
                post(() -> {

                    //  计算当前值
                    int height = barLL.getHeight();
                    int index;
                    if (ey <= 0) {
                        index = 0;
                    } else if (ey >= height) {
                        index = 25;
                    } else {
                        index = (int) (ey / (height / 26.0));
                    }

                    //  设置当前值
                    setCurrentIndex(index);

                    //  移动RV至对应位置
                    if (rv == null) {
                        return;
                    }
                    SortClubAdapter adapter = (SortClubAdapter) rv.getAdapter();
                    if (adapter == null) {
                        return;
                    }
                    int itemIndex = adapter.getItemIndexByCurrent(String.valueOf((char) ('A' + index)));
                    if (itemIndex == -1) {
                        return;
                    }
                    //  开始滑动
                    LinearSmoothScroller smoothScroller = new LinearSmoothScroller(getContext()) {
                        @Override
                        protected int getHorizontalSnapPreference() {
                            return LinearSmoothScroller.SNAP_TO_START;
                        }

                        @Override
                        protected int getVerticalSnapPreference() {
                            return LinearSmoothScroller.SNAP_TO_START;
                        }
                    };
                    smoothScroller.setTargetPosition(itemIndex);
                    Objects.requireNonNull(rv.getLayoutManager()).startSmoothScroll(smoothScroller);
                });
            }

            performClick();

            return false;
        });
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    public void setCurrentIndex(int index) {
        if (index < 0) {
            index = 0;
        }
        else if (index > 25) {
            index = 25;
        }

        //  将视图样式复原
        for (TextView textView : textViewList) {
            textView.setBackgroundColor(getResources().getColor(R.color.transparent));
            textView.setTextColor(getResources().getColor(R.color.primary_text));
        }

        //  设置当前值
        String current = String.valueOf((char) ('A' + index));
        currentView.setText(current);
        TextView textView = textViewList.get(index);
        textView.setBackground(getResources().getDrawable(R.drawable.sort_list_bar_item_bg));
        textView.setTextColor(getResources().getColor(R.color.white_text));

        this.currentIndex = index;
    }

    public int getCurrentIndex() {
        return currentIndex;
    }

    public RecyclerView getRv() {
        return rv;
    }

    public void setRv(RecyclerView rv) {
        this.rv = rv;
    }
}
